package com.jsz.yun.ai.field.domainservice.impl;

import cn.hutool.core.lang.UUID;
import com.jsz.yun.ai.field.domainservice.UserFileDomainService;
import com.jsz.yun.ai.field.entity.UserEntity;
import com.jsz.yun.ai.field.entity.UserFileEntity;
import com.jsz.yun.ai.field.repository.MinIoFileService;
import com.jsz.yun.ai.field.repository.UserFileInfoRepository;
import com.jsz.yun.ai.field.util.ThreadLocalSetting;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * @author gaoxing
 * @date 2025-03-28 16:58:05
 */
@Service
@Slf4j
public class UserFileDomainServiceImpl implements UserFileDomainService {

    @Resource
    private UserFileInfoRepository userFileInfoRepository;

    @Resource
    MinIoFileService minIoFileService;
    @Override
    public UserFileEntity uploadFile(MultipartFile file, String name) {
        UserEntity userEntity = ThreadLocalSetting.USER_FILE_THREADLOCAL.get();
        long size = file.getSize();
        log.info("上传文件大小：{}", size);
        String filename = null;
        long subTaskId = UUID.fastUUID().getLeastSignificantBits();
        filename = file.getOriginalFilename();
        filename = name + "/" + filename;
        log.info("上传文件名称：{}", filename);
        String downUrl = minIoFileService.uploadFile(file, filename);
        //存数据库
        UserFileEntity fileEntity = new UserFileEntity();
        fileEntity.setUserId(userEntity.getUserId());
        fileEntity.setFileId(String.valueOf(subTaskId));
        fileEntity.setFileUrl(downUrl);
        fileEntity.setFileName(filename);
        fileEntity.setFileSize(String.valueOf(size));
        fileEntity.setFileType(file.getContentType());
        return userFileInfoRepository.insertFile(fileEntity);
    }
}
